<?php


namespace WxWorkSDK\Member;


use WxWorkSDK\Error\Error;
use WxWorkSDK\Http\Http;
use WxWorkSDK\Result;

class UserList
{
    const URI        = "user/list";
    const SIMPLE_URI = "user/simplelist";
    /**
     * @var string
     * @annotation
     */
    public $accessToken = '';
    /**
     * @var int|null
     * @annotation
     */
    public $departmentId = NULL;
    /**
     * @var int
     * @annotation
     */
    public $fetchChild;

    public function __construct(string $accessToken, int $departmentId, int $fetchChild = 0)
    {
        $this->accessToken  = $accessToken;
        $this->departmentId = $departmentId;
        $this->fetchChild   = $fetchChild;
    }

    public function list()
    {
        if ($check = $this->check() != 0) {
            return new Result(FALSE, Error::PARAM_MISTAKE, $check);
        }
        list($bool, $response) = Http::request('POST', self::URI, ['query' => [
            'access_token'  => $this->accessToken,
            'department_id' => $this->departmentId,
            'fetch_child'   => $this->fetchChild
        ]]);
        if ($bool) {
            return $this->response($response);
        } else {
            return $response;
        }
    }

    public function simpleList()
    {
        if ($check = $this->check() != 0) {
            return new Result(FALSE, Error::PARAM_MISTAKE, $check);
        }
        list($bool, $response) = Http::request('POST', self::SIMPLE_URI, ['query' => [
            'access_token'  => $this->accessToken,
            'department_id' => $this->departmentId,
            'fetch_child'   => $this->fetchChild
        ]]);
        if ($bool) {
            return $this->response($response);
        } else {
            return $response;
        }
    }

    public function check()
    {
        if (empty($this->accessToken)) {
            return '无TOKEN';
        }
        if (empty($this->departmentId)) {
            return '无部门id';
        }
        return 0;
    }

    /**
     * @param $response
     * @return Result
     * @annotation
     */
    private function response($response): Result
    {
        $response = json_decode($response, TRUE);
        if ($response['errcode'] == 0) {
            return new Result(TRUE, 0, 'ok', $response['userlist']);
        } else {
            return new Result(FALSE, Error::WX_MISTAKE, $response['errcode'] . ':' . $response['errmsg']);
        }
    }
}